import React from 'react';
import {
  Badge, Button, Card, Col, Drawer,
  Empty, Layout, Row, Tag, Tree,
} from 'antd';
import { Form, Icon } from '@ant-design/compatible';
import { PageHeaderLayout, StandardTable, SearchForm } from '../../components';
import { connect } from 'dva';
import { modalWidth, pageSize } from '../../../config';
import styles from './assign.css';
import tools from '../../utils';

const reqApi = 'assign';
const { Sider, Content } = Layout;
const { TreeNode } = Tree;
const { CheckableTag } = Tag;
const statusData = [
  [5, '待分配'],
  [6, '已分配'],
];
const statusMapping = {};

class page extends React.Component {
  state = {
    currentNavi: '',
    loadingNavi: false,
    loadingContent: false,
    dialogLoading: false,
    record: {},
    selectedRows: [],
    searchs: [],
    pagination: {
      current: 1,
      pageSize,
      onShowSizeChange: (_, size) => {
        const { pagination } = this.state;
        pagination.pageSize = size;
      },
    },
  };

  constructor(props) {
    super(props);
    statusData.map((item) => {
      const [key, value] = item;
      statusMapping[key] = value;
    });
  }

  componentDidMount() {
    this.funcGetNaviData();
    this.funcGetListData();
  }

  // 获取菜单数据
  funcGetNaviData = () => {
    this.setState({ loadingNavi: true });

    const { props } = this;
    props.dispatch({
      type: reqApi + '/listSpecial',
      payload: { currentPage: 1, pageSize: 1000 },
    }).then(() => this.setState({ loadingNavi: false }));
  };

  // 获取班级数据
  funcGetClassroomData = (specialId) => {
    const searchs = [];
    if (specialId) {
      searchs.push({
        name: 'specialId',
        value: specialId,
        searchType: 'EQ',
        dataType: 'STR',
      });
    }
    const { dispatch } = this.props;
    dispatch({
      type: reqApi + '/listClassroom',
      payload: {
        currentPage: 1,
        pageSize: 1000,
        searchs,
      },
    });
  };

  // 获取宿舍数据
  // params: (sex="1" or "0")
  funcGetDormitoryData = (sex) => {
    const searchs = [];
    if (sex) {
      searchs.push({
        name: 'type',
        value: sex,
        searchType: 'EQ',
        dataType: 'STR',
      });
    }
    const { dispatch } = this.props;
    dispatch({
      type: reqApi + '/listDormitory',
      payload: {
        currentPage: 1,
        pageSize: 1000,
        searchs,
      },
    });
  };

  // 获取列表数据
  funcGetListData = () => {
    this.setState({
      loadingContent: true,
      selectedRows: [],
    });

    const { state } = this;
    const { searchs, pagination } = state;
    const { current, pageSize } = pagination;
    const { dispatch } = this.props;
    const newSearchs = [...searchs];

    if (state.currentNavi) {
      newSearchs.push({
        name: 'i.special_id',
        value: state.currentNavi,
        searchType: 'EQ',
        dataType: 'STR',
      });
    }

    dispatch({
      type: reqApi + '/list',
      payload: {
        currentPage: current,
        pageSize,
        searchs: newSearchs,
      },
    }).then(() => this.setState({ loadingContent: false }));
  };

  // 弹出表单
  funcOpenForm = (record) => {
    this.setState({
      record,
      visible: true,
    });

    const { specialId } = record;
    this.funcGetClassroomData(specialId);

    if (record.lodging === '0') return;

    const { sex } = record;
    this.funcGetDormitoryData(sex);
  };

  // 保存
  funcSave = () => {
    const { state } = this;
    const { form, dispatch } = this.props;

    form.validateFields((error, values) => {
      if (error) return error;

      const model = { ...values };
      model.studentId = state.record.id - 0;
      model.classroomId -= 0;
      model.dormitoryId -= 0;

      this.setState({ dialogLoading: true });

      dispatch({
        type: reqApi + '/assign',
        payload: { ...model },
      }).then(() => {
        this.setState({ dialogLoading: false });

        const { props } = this;
        const { success } = props[reqApi];
        if (success) {
          this.setState({ visible: false });
          this.funcGetListData();
        }
      });
    });
  };

  // 树实体
  treeBody = (data) => {
    return data.map((item) => {
      const { key, title } = item;
      return <TreeNode key={key} title={title} />;
    });
  };

  // 导航菜单
  naviMenu = () => {
    const { props } = this;
    const data = props[reqApi].dataSpecial;

    if (data.length) {
      return (
        <div style={{ maxHeight: 'calc(100vh - 120px)', overflow: 'auto' }}>
          <Tree
            blockNode
            defaultExpandAll
            onSelect={(selectedKeys) => {
              this.setState({
                currentNavi: selectedKeys.length ? selectedKeys[0] : "",
              }, this.funcGetListData);
            }}
          >
            {this.treeBody(data)}
          </Tree>
        </div>
      );
    } else return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
  };

  // 表格列
  columns = [
    {
      title: '报考专业',
      dataIndex: 'specialName',
    },
    {
      title: '学生姓名',
      dataIndex: "name",
      width: 100,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      width: 50,
      render: text => text === '1' ? '男' : '女',
    },
    {
      title: '是否住校',
      dataIndex: 'lodging',
      width: 80,
      render: text => text === '1' ? '住校' : '不住校',
    },
    {
      title: '分配班级',
      dataIndex: 'classroomName',
      width: 100,
    },
    {
      title: '分配宿舍',
      dataIndex: 'dormitoryName',
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      render: (text, record) => record.status === '5' ? (
        <Badge dot>
          <a onClick={() => this.funcOpenForm(record)}>
            {statusMapping[text]}
          </a>
        </Badge>
      ) : (
        <div>
          <Icon
            type='check-circle'
            theme='twoTone'
            twoToneColor='limegreen'
            style={{ fontSize: 16 }}
          />
          <span style={{ color: 'limegreen' }}>
            {' ' + statusMapping[text]}
          </span>
        </div>
      ),
    },
  ];

  // 查询列
  columnsSearch = [
    {
      title: '状态',
      dataIndex: 'i.`status`',
      type: 'select',
      sub: statusData,
    },
    {
      title: '学生姓名',
      dataIndex: 'i.`name`',
      type: 'text',
    },
    {
      title: '性别',
      dataIndex: 'i.sex',
      type: 'select',
      sub: [
        [1, '男'],
        [0, '女'],
      ],
    },
  ];

  // 记录查询表单提交
  funcOnSubmitSearch = (searchs) => {
    const { state } = this;
    state.pagination.current = 1; // 进行查询操作则将页码归一
    this.setState({ searchs }, this.funcGetListData);
  };

  // 内容列表
  contentTable = () => {
    const { state, props } = this;
    const { data, total } = props[reqApi];

    return (
      <div>
        <SearchForm fields={this.columnsSearch} onSubmit={this.funcOnSubmitSearch} />

        <StandardTable
          loading={state.loadingContent}
          columns={this.columns}
          data={{
            list: data,
            pagination: { ...state.pagination, total },
          }}
          selectedRows={state.selectedRows}
          onSelectRow={(selectedRows) => this.setState({ selectedRows })}
          onChange={(pageParams) => {
            const { pagination } = this.state;
            pagination.current = pageParams.current;
            this.funcGetListData();
          }}
        />
      </div>
    );
  };

  render() {
    const { state, props } = this;
    const { record } = state;
    const { form } = props;
    const { getFieldDecorator } = form;
    const { dataClassroom, dataDormitory } = props[reqApi];

    return (
      <PageHeaderLayout title={props.route.name}>
        <Card bordered={false} bodyStyle={{ padding: 0 }}>
          <Layout>
            <Sider
              theme="light"
              style={{
                borderRight: "1px solid gainsboro",
              }}>
              {this.naviMenu()}
            </Sider>
            <Content
              style={{
                padding: "16px 8px 0 8px",
                backgroundColor: "white",
              }}>
              {this.contentTable()}
            </Content>
          </Layout>
        </Card>

        <Drawer
          width={modalWidth}
          title={(
            <div>
              <Icon type='user' style={{ fontSize: 16 }} />
              <span> 分配班级和宿舍</span>
            </div>
          )}
          visible={state.visible}
          onClose={() => this.setState({ visible: false })}
          bodyStyle={{ paddingLeft: 0, paddingRight: 0 }}
          drawerStyle={{ overflow: 'hidden' }}
        >
          <div
            style={{
              height: 'calc(100vh - 130px)',
              overflow: 'auto',
              padding: '0 24px',
            }}
          >
            <table className={styles.table}>
              <tbody>
              <tr>
                <th>学生姓名</th><td>{record.name}</td>
                <th>性别</th><td>{record.sex === '1' ? '男' : '女'}</td>
                <th>联系电话</th><td>{record.phone}</td>
              </tr>
              <tr>
                <th>是否住校</th><td>{record.lodging === '1' ? '是' : '否'}</td>
                <th>报考专业</th><td colSpan={3}>{record.specialName}</td>
              </tr>
              </tbody>
            </table>

            <Form>
              <Row gutter={{ md: 24, sm: 8 }}>
                <Col md={record.lodging === '1' ? 12 : 24} sm={24}>
                  <Form.Item label='分配班级'>
                    {getFieldDecorator('classroomId', {
                      rules: [{ required: true, message: '请选择班级' }],
                    })(
                      <div className={styles.box}>
                        {dataClassroom.map((item) => {
                          const { id, name, num, size } = item;
                          if (num < size) {
                            return (
                              <CheckableTag
                                key={id}
                                className={styles.tag}
                                checked={id === form.getFieldValue('classroomId')}
                                onChange={(checked) => {
                                  form.setFieldsValue({ classroomId: checked ? id : '' });
                                }}
                              >
                                <div>{name}</div>
                                <div>{num + '/ ' + size}</div>
                              </CheckableTag>
                            );
                          }
                          return (
                            <Tag key={id} className={styles.tag0}>
                              <div>{name}</div>
                              <div>{num + '/ ' + size}</div>
                            </Tag>
                          );
                        })}
                      </div>
                    )}
                  </Form.Item>
                </Col>

                {record.lodging === '1' ? (
                  <Col md={12} sm={24}>
                    <Form.Item label='分配宿舍'>
                      {getFieldDecorator('dormitoryId', {
                        rules: [{ required: true, message: '请选择宿舍' }],
                      })(
                        <div className={styles.box}>
                          {dataDormitory.map((item) => {
                            const { id, name, num, size } = item;
                            if (num < size) {
                              return (
                                <CheckableTag
                                  key={id}
                                  className={styles.tag}
                                  checked={id === form.getFieldValue('dormitoryId')}
                                  onChange={(checked) => {
                                    form.setFieldsValue({ dormitoryId: checked ? id : '' });
                                  }}
                                >
                                  <div>{name}</div>
                                  <div>{num + '/ ' + size}</div>
                                </CheckableTag>
                              );
                            }
                            return (
                              <Tag key={id} className={styles.tag0}>
                                <div>{name}</div>
                                <div>{num + '/ ' + size}</div>
                              </Tag>
                            );
                          })}
                        </div>
                      )}
                    </Form.Item>
                  </Col>
                ) : null}
              </Row>
            </Form>
          </div>

          <div
            style={{
              borderTop: '1px solid gainsboro',
              padding: '10px 16px',
              textAlign: 'right',
            }}
          >
            <Button onClick={() => this.setState({ visible: false })}>
              {tools.funcDlgBtnCancel()}
            </Button>
            {record.status === '5' ? (
              <Button
                type='primary'
                loading={state.dialogLoading}
                onClick={this.funcSave}
                style={{ marginLeft: 8 }}
              >
                {state.dialogLoading ?
                  '确认分配' :
                  tools.funcDlgBtnSave('确认分配', 'check')
                }
              </Button>
            ) : null}
          </div>
        </Drawer>
      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ assign }) => ({ assign }))(page2);
